import jquery from 'jquery'

const $: JQueryStatic = jquery

function doExport(): void {
    let table: HTMLElement | undefined =
        Array.from(document.querySelectorAll('span')).find(el => el.textContent === '数据点设置')
    if (table === undefined) return
    table = table.nextSibling as HTMLElement
    const dataPoints = Array.from(table.children[0].children).slice(2)
    let yaml = ''
    for (const dataPoint of dataPoints) {
        const name = (dataPoint.children[0] as HTMLElement).innerText.match(/#\d+:\s(.+\.in)/)?.[1] ?? ''
        const time = (dataPoint.children[1].children[0].children[0] as HTMLInputElement).value
        const memory = (dataPoint.children[2].children[0].children[0] as HTMLInputElement).value
        const subtaskId = (dataPoint.children[3].children[0].children[0] as HTMLInputElement).value
        const score = (dataPoint.children[4].children[0].children[0] as HTMLInputElement).value

        const entry = `${name}:
    timeLimit: ${time}
    memoryLimit: ${parseInt(memory) * 1000}
    subtaskId: ${subtaskId}
    score: ${score}\n\n`

        yaml += entry
    }

    const file = new Blob([yaml], { type: 'text/yaml' })
    const a = document.createElement('a'); const url = URL.createObjectURL(file)
    a.href = url
    a.download = 'config.yml'
    document.body.appendChild(a)
    a.click()
    setTimeout(function() {
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
    }, 0)
}

function checkUrl(): boolean {
    const url = window.location.href
    return url.match(/^https?:\/\/www\.luogu\.com\.cn\/problem\/edit\/.*$/) !== null
}

async function load(): Promise<void> {
    if (!checkUrl()) return
    await new Promise<void>((resolve, _reject) => {
        const id = setInterval(() => {
            if (window.location.href.endsWith('#data')) {
                clearInterval(id)
                resolve()
            }
        }, 2000)
    })
    setTimeout(() => {
        const el = (Array.from(document.querySelectorAll('span')).find(el => el.textContent === '上传/下载')
            ?.nextSibling as HTMLElement).children[0]
        // noinspection HtmlUnknownAnchorTarget
        const btn = $(`
        <a type='button' class="btn lfe-form-sz-middle" href="#data">
             导出 yaml 配置
        </a>
        `)
        btn.on('click', doExport)
        $(el).append(btn)
    }, 1000)
}

export { load }
